package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"github.com/faiface/beep"
	"github.com/faiface/beep/speaker"
	"github.com/fatih/color"
	"log"
	"music/api"
	"music/play"
	"music/prompt"
	"music/utils"
	"os"
)

var (
	keyword, operate string
	res              api.SearchResult
	//detailResult  api.DetailResult
	selectMusicId int
)

func check(err error) {
	if err != nil {
		log.Fatalln(err.Error())
	}
}
func catch() {
	if err := recover(); err != nil {
		log.Printf("something is wrong: %v", err)
	}
}
func main() {
	defer catch()
	prompt.Tips()

	_, err := fmt.Fscan(bufio.NewReader(os.Stdin), &keyword)
	check(err)

	prompt.Searching(keyword)

	result, err := api.Search(keyword)
	check(err)
	err = json.Unmarshal([]byte(result), &res)
	check(err)

	utils.PrintMscTable(res.Data.Songs)

InputNo:
	color.Yellow("请选择你要操作的序号")
	_, _ = fmt.Fscan(bufio.NewReader(os.Stdin), &selectMusicId)
	if len(res.Data.Songs) < selectMusicId || selectMusicId < 1 {
		color.Red("输入正确的序号数字")
		prompt.Wait()
		goto InputNo
	}

	ms := &play.MusicEntry{
		Libs:       res.Data.Songs,
		NowInx:     selectMusicId - 1,
		Name:       res.Data.Songs[selectMusicId-1].Name,
		FileStream: nil,
	}

	done := make(chan bool)
	var ctrl *beep.Ctrl
	ms.Open()
	go ms.Play(done, &ctrl)
	for {
		_, _ = fmt.Fscan(bufio.NewReader(os.Stdin), &operate)
		switch {
		case operate == "i":
			speaker.Lock()
			ctrl.Paused = !ctrl.Paused
			if ctrl.Paused {
				fmt.Println("已暂停")
			} else {
				fmt.Println("已恢复")
			}
			speaker.Unlock()
		case operate == "n":
			speaker.Close()
			done <- true
		default:
			goto InputNo
		}

	}
}
